/*
 * ============================================================================
 *
 *       Filename:  list.c
 *
 *
 *        Created:  10/04/2011 05:47:19 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  durand_y, <durand.yoan@gmail.com>
 *
 * ============================================================================
 */
#include "list.h"
#include "find.h"
#include <stdio.h>

s_list              *init(void)
{
    s_list  *list = NULL;

    list = malloc(sizeof (s_list));
    list->dir = NULL;
    list->next = NULL;
    list->size = 0;
    return (list);
}

s_list              *add(s_list         *list,
                         char           *elt)
{
    s_list  *p = NULL;
    s_list  *aux = NULL;

    if (list->size == 0)
    {
        list->dir = elt;
        list->next = NULL;
        list->size++;
    }
    else
    {
        aux = init();
        aux->dir = elt;
        p = list;
        while(p->next != NULL)
            p = p->next;
        p->next = aux;
        list->size++;
    }
    return (list);
}

s_list              *del(s_list         *list,
                         char           *elt)
{
    s_list          *p = NULL;
    s_list          *prev = NULL;

    if (mystrcmp(list->dir, elt) == 1)
    {
        p = list;
        list = list->next;
        free(p);
        p = NULL;
    }
    else
    {
        p = list;
        prev = p;
        while ((p != NULL) && (mystrcmp(extract_end(p->dir), elt) == 0))
        {
            prev = p;
            p = p->next;
        }
        if (p != NULL)
        {
            prev->next = p->next;
            list->size--;
            free(p);
        }
    }
    return (list);
}

int                print(s_list        *list)
{
    s_list         *p = NULL;
    int            err = 0;

    if (list->size >0)
    {
        p = list;
        while(p != NULL)
        {
            write(STDOUT_FILENO, p->dir, mystrlen(p->dir));
            write(STDOUT_FILENO, "\n", 1);
            if (permission(p->dir) == 0)
            {
                my_error("./find: `", p->dir);
                err = 1;
            }
            p = p->next;
        }
        free(p);
        clear(list);
    }
    return (err);
}

char                *search_elt(s_list  *list,
                                char    *elt)
{
    s_list          *p = NULL;
    char            *buff = NULL;
    p = list;

    while (p != NULL)
    {
        buff = extract_end(p->dir);
        if (mystrcmp(buff, elt) == 1)
            return (p->dir);
        p = p->next;
    }
    return (NULL);
}
